﻿using System.IO;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Xps.Packaging;

namespace Open.Infrastructure
{
    #region How to use
    //     foreach (UIElement item in control.Children)
    //            {
    //                list.Add(CloneControl(item));
    //            }
    //XpsReader x = new(list.ToArray(), true, OrderModel.AccessionNumber);
    #endregion
    /// <summary>
    /// XpsReader.xaml 的交互逻辑
    /// </summary>
    public partial class XpsReader : Window
    {
        private string AccessionNumber;
        private readonly string BaseDir = $@"{System.AppDomain.CurrentDomain.BaseDirectory}\Report";
        /// <summary>
        /// 构造函数，弹窗预览
        /// </summary>
        /// <param name="obj">打印内容</param>
        public XpsReader(object[] obj)
        {
            InitializeComponent();

            OrganizationPrintingStructure(obj);
        }

        /// <summary>
        ///  构造函数，直接打印
        /// </summary>
        /// <param name="obj">打印内容</param>
        /// <param name="a">用来判断是否直接打印</param>
        public XpsReader(object[] obj, bool a,string assessionno="")
        {
            InitializeComponent();
            AccessionNumber = assessionno;
            OrganizationPrintingStructure(obj);
            docView.PrintwithoutDialog(docView.Document as FixedDocument);
        }

        /// <summary>
        /// 组织打印结构
        /// </summary>
        /// <param name="obj">打印内容</param>
        private void OrganizationPrintingStructure(object[] obj)
        {
            FixedDocument fixedDoc = new();
            foreach (var item in obj)
            {
                PageContent pageContent = new();
                FixedPage fixedPage = new();
                UIElement visual = (UIElement)item;
                _ = fixedPage.Children.Add(visual);
                ((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage);
                _ = fixedDoc.Pages.Add(pageContent);
            }
            SaveXps(fixedDoc, $@"{BaseDir}/{AccessionNumber}.xps");
            PdfFilePrinter.PrintFile($@"{BaseDir}/{AccessionNumber}.xps", $@"{BaseDir}/{AccessionNumber}.pdf");
            docView.Document = fixedDoc;
        }

        private void SaveXps(FixedDocument fixedDoc, string xpsFilePath)
        {
            if (!Directory.Exists($@"{BaseDir}"))
                Directory.CreateDirectory($@"{BaseDir}");
            if (File.Exists(xpsFilePath))
                File.Delete(xpsFilePath);
            var paginator = fixedDoc.DocumentPaginator;
            var xpsDocument = new XpsDocument(xpsFilePath, FileAccess.Write);
            var documentWriter = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
            documentWriter.Write(paginator);
            xpsDocument.Close();
        }
    }
}
